/**
 * @author 雷明浩
 * @date 2025/5/29 11:26
 */
public class MergeKLists {
    // leetcode 合并k个升序链表
    // https://leetcode.cn/problems/merge-k-sorted-lists/?envType=study-plan-v2&envId=top-100-liked
    public ListNode mergeKLists(ListNode[] lists) {
        if (lists.length == 0) return null;
        return mergeKListsChild(lists, 0, lists.length - 1);
    }

    private ListNode mergeKListsChild(ListNode[] lists, int left, int right) {
        if (left >= right) {
            return lists[left];
        }
        int mid = left + (right-left) / 2;
        ListNode leftList = mergeKListsChild(lists, left, mid);
        ListNode rightList = mergeKListsChild(lists, mid+1, right);
        return merge(leftList, rightList);
    }

    private ListNode merge(ListNode head1, ListNode head2) {
        ListNode phead = new ListNode();
        ListNode cur = phead;
        ListNode cur1 = head1;
        ListNode cur2 = head2;
        while (cur1 != null && cur2 != null) {
            if(cur1.val <cur2.val) {
                cur.next = cur1;
                cur1 = cur1.next;
            }else {
                cur.next = cur2;
                cur2 = cur2.next;
            }
            cur = cur.next;
        }
        if (cur1 != null) {
            cur.next = cur1;
        }
        if (cur2 != null) {
            cur.next = cur2;
        }
        return phead.next;
    }
}